package com.lz.filter;

import com.alibaba.fastjson.JSON;
import com.lz.domain.MyUserDetails;
import com.lz.utils.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * <pre>
 * @描述：
 * @作者：lizhao
 * @创建时间： 2024/8/19 下午3:53
 * </pre>
 **/
@Slf4j
@Component
public class SecurityFilter extends OncePerRequestFilter {

    private final String TOKEN = "token";

    @Resource
    private RedisTemplate redisTemplate;

    /**
     * 需要在Security中配置
     * 用户进入过滤器，
     * 在用户登录，将详细信息以JSON的格式存入redis中，
     * 对于后续，通过token获取用户详细信息，从而给用户赋权限
     */
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        //放通登录方法
        if (request.getRequestURI().contains("/user/login")) {
            filterChain.doFilter(request, response);
            return;
        }

        //无token的，直接进入下一个拦截器
        String header = request.getHeader(TOKEN);
        if (header == null || header.trim().isEmpty()) {
            // 处理JWT令牌不存在的情况，例如返回401 Unauthorized
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return;
        }

        // 从JWT中获取用户ID
        String userid = JwtUtil.getSubjectFromToken(header);
        if (userid == null) {
            // 处理无效的JWT
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            return;
        }

        // 安全地从Redis获取MyUserDetails对象
        Object obj = redisTemplate.opsForValue().get(userid);
        if (obj == null) {
            // 处理缓存中没有用户详情的情况
            log.warn("User details not found in cache for user ID: {}", userid);
            // 可以返回一个错误或者执行其他逻辑
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            return;
        }

        // 确保类型转换是安全的
        MyUserDetails userDetails = JSON.parseObject(String.valueOf(obj), MyUserDetails.class);
        // 使用userDetails进行后续操作
        log.info("User details retrieved from cache: {}", userDetails);

        UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(token);
        filterChain.doFilter(request, response);
    }
}
